package net.wanho.config;

import net.wanho.shiro.filter.JwtFilter;
import net.wanho.shiro.matcher.JwtMatcher;
import net.wanho.shiro.realm.ShiroRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Author：汤小洋
 * Date：2023-07-25 16:43
 * Description：<描述>
 */
@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        filterFactoryBean.setSecurityManager(securityManager);

        // 自定义过滤器
        Map<String, Filter> filterMap = new HashMap<>();
        filterMap.put("jwtFilter", new JwtFilter());
        filterFactoryBean.setFilters(filterMap);

        //设置过滤的url
        Map<String,String> map = new LinkedHashMap<>();
        map.put("/captchaImage","anon");
        map.put("/login","anon");
        // 放行knife4j
        map.put("/doc.html", "anon");
        map.put("/webjars/**", "anon");
        map.put("/swagger-resources/**", "anon");
        map.put("/v2/api-docs/**", "anon");
        map.put("/knife4j/**", "anon");

        map.put("/**","jwtFilter");
        filterFactoryBean.setFilterChainDefinitionMap(map);

        return filterFactoryBean;
    }

    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(realm);
        return securityManager;
    }

    @Bean
    public Realm getShiroRealm(){
        ShiroRealm shiroRealm = new ShiroRealm();

        // 使用JwtMatcher进行认证
        JwtMatcher jwtMatcher = new JwtMatcher();
        shiroRealm.setCredentialsMatcher(jwtMatcher);
        return shiroRealm;
    }

}
